<?php
abstract class soap_alphabet_base
{
	/**
	 * Elements
	 *
	 * @var soap_array_base
	 */
	public $Elements = array();


	/**
	 * Save to DB
	 *
	 * @return int index of saved alphabet
	 */
	public function save_to_db() {
		$dba = db_adapter::get_instance();
		$messages_ids = $this->get_elements_id_array();

		
		
		$alphabet_id = $this->get_alphabet_id_equals_this($messages_ids);
		
			
		if (empty($alphabet_id))
		{
			$alphabet_id = $this->save_new_alphabet();
			$this->save_message_to_alphabet($alphabet_id, $messages_ids);
		}
		return $alphabet_id;
	}

	/**
	 * Get id of alphabet contains this elements
	 *
	 * @param array $phantom_messages_ids
	 * @return int
	 */
	abstract protected function get_alphabet_id_equals_this($phantom_messages_ids);


    /**
     * Get array of elements_id.
     * If elements is not in DB.
     * Save it.
     *
     * @return array
     */
    protected function get_elements_id_array()
    {
        $messages_ids = array();
        foreach($this->Elements->as_array() as $soap_message){
            $messages_ids[] = $soap_message->save_to_db();
        }            
        return array_unique($messages_ids);
    }


	/**
	 * Save messages to alphabet
	 *
	 * @param int $alphabet_id
	 * @param array $phantom_messages_ids
	 */
	abstract protected function save_message_to_alphabet($alphabet_id , $phantom_messages_ids);

	/**
	 * Create new Alphabet in DB
	 *
	 * @return int created alphabet
	 */
	protected function save_new_alphabet($type)
	{
		$dba = db_adapter::get_instance();
		$to_get_id = new alphabet();
		$dba->get_last_id($to_get_id);

		$alphabet = new alphabet();
		$new_count = $to_get_id->alphabet_id->get_value() + 1;
		$alphabet_name = "_".$new_count;
		$alphabet->alphabet_type->set_value($type);
		$alphabet->alphabet_name->set_value($alphabet_name);
		$dba->save_unique($alphabet);
		return $alphabet->alphabet_id->get_value();
	}
}
?>